def read_words(line):
    sz = len(line)
    words = []
    i = 0
    while i < sz:
        while i < sz and line[i] == " ":
            i += 1
        word = ""
        while i < sz and line[i] != " ":
            word += line[i]
            i += 1
        word = word.strip()
        if len(word) > 0:
            words.append(word)
    return words

def to_markdown_table(content):
    if len(content) < 2:
        return ""
    head = content[0]
    body = content[1:]
    n = len(head)
    if n == 0:
        return ""
    head_text = " ".join(["|" for x in range(0, n + 1)])
    head_text = "|" + " | ".join(head) + "|" + "\n" + head_text.replace(" ", "--") + "\n"
    body_text = ""
    for item in body:
        body_text +="|" + "|".join([f" {x} " for x in item]) + "|"
        body_text += "\n"
    return head_text + body_text

def parse(file_path):
    with open(file_path, "r", encoding="utf-8") as fp:
        lines = fp.readlines()
        from_tos = []
        i = 0
        while i < len(lines):
            if lines[i].strip().startswith("字段名称"):
                _from = i
                i += 1
                while i < len(lines) and lines[i].strip().startswith("field"):
                    i += 1
                from_tos.append([_from, i])
                i -= 1
            i += 1
        new_lines = []
        is_add = set()
        for i in range(0, len(lines)):
            in_from_tos = False
            for item in from_tos:
                if i >= item[0] and i < item[1]:
                    in_from_tos = True
                    if str(item) not in is_add:
                        texts = lines[item[0]: item[1]]
                        content = [read_words(x) for x in texts]
                        new_lines.append(to_markdown_table(content))
                        is_add.add(str(item))
            if not in_from_tos:
                new_lines.append(lines[i] + "\n")
        return "".join(new_lines)

file_name = './波刺评审会.txt'

with open(file_name + '-parse.txt','w' ,encoding='utf-8') as fp:
    fp.write(parse(file_name))

